package com.extrace.server.service;

import com.extrace.server.dao.CustomerDao;
import com.extrace.server.pojo.Customer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CustomerService {
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private RegionService regionService;


    public Customer getCurrentCustomer() {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            // Assumes the principal stored is the customer's telephone code
            String telCode = currentUser.getPrincipal().toString();
            Customer customer = findByTelCode(telCode);
            return customer;
        }
        return null; // 或者抛出未认证异常，根据你的应用需求
    }

    public void addInfo(Customer customer) {
        if (customer == null) {
            return;
        }
        if (customer.getRegionCode() != null) {
            customer.setRegion(regionService.findAllByRegionCode(customer.getRegionCode()));
        }
    }

    public void deleteInfo(Customer customer) {
        if (customer == null) {
            return;
        }
        customer.setSalt(null);
        customer.setPassword(null);
    }

    public List<Customer> findByName(String name) {
        return customerDao.findByNameLike(name);
    }

    public Customer findByTelCode(String telCode) {
        Customer byTelCode = customerDao.findByTelCode(telCode);
        if (byTelCode != null) {
            System.out.println(byTelCode.toString());
        } else {
            System.out.println("customer is null");
        }
        return byTelCode;
    }

    public Customer findById(int id) {
        Customer customer = customerDao.findById(id);
        return customer;
    }

    public Customer deleteById(int id) {
        Customer c = findById(id);
        customerDao.delete(c);
        return c;
    }

    public Customer save(Customer c) {
        customerDao.save(c);
        return c;
    }
}
